import Vue from 'vue'
import Router from 'vue-router'
import axios from 'axios'
import index from '@/components/index'
// import head from '@/components/head'
import list from '@/components/list'
import detail from '@/components/detail'
import cart from '@/components/cart'
import order from '@/components/order'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'index',
      component: index
    },
    {
      path: '/list/:sid/:search',
      name: 'list',
      component: list,
      props: true
    },
    {
      path: '/detail/:id',
      name: 'detail',
      component: detail,
      props: true
    },
    {
      path: '/cart',
      name: 'cart',
      component: cart,
      props: true
    },
    {
      path: '/order/:id',
      name: 'order',
      component: order,
      props: true
    }
  ]
})
// http request 拦截器
axios.interceptors.request.use(
  config => {
    let token = window.localStorage.getItem('Booktoken')
    console.log(token)
    if (token) { // 判断是否存在token，如果存在的话，则每个http header都加上token
      //   config.headers.Authorization = `Bearer ${token}`;
      config.headers.Authorization = 'Bearer ' + token
      console.log(config.headers.Authorization)
    }
    console.log('我在申请返回信息')
    return config
  },
  err => {
    return Promise.reject(err)
  }
)
// http response 拦截器
axios.interceptors.response.use(
  response => {
    console.log('我正在返回信息')
    return response.data
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          localStorage.removeItem('Booktoken')
          router.replace({
            path: '/',
            query: {redirect: router.currentRoute.fullPath}
          })
      }
    }
    return Promise.reject(error.response)
    // return Promise.reject(error.response.data)   // 返回接口返回的错误信息
  }
)
export default router
